﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Pavilion.DesignerTool.ViewTools.ConnectableListBox;

namespace Pavilion.DesignerTool.NodeDesignerTool.Scripting
{
    public class NodeLayoutSerializer
    {
        public XDocument SerializeCollection(IConnectableItem containerNode)
        {
            XDocument xmlDocument = new XDocument();
            xmlDocument.Add(new XElement("Script", SerializeContainer(containerNode)));

            return xmlDocument;
        }

        private XElement SerializeContainer(IConnectableItem containerNode)
        {
            XElement BaseWrapperXElement = SerializeNode(containerNode as NodeBaseWrapper);

            foreach (NodeBaseWrapper nodeWrapper in (containerNode as ContainerNodeWrapper).ConnectableItems)
            {
                if (nodeWrapper is IConnectableItemContainer)
                    BaseWrapperXElement.Add(SerializeContainer(nodeWrapper));
                else
                    BaseWrapperXElement.Add(SerializeNode(nodeWrapper));
            }

            return BaseWrapperXElement;
        }

        private XElement SerializeNode(NodeBaseWrapper nodeBaseWrapper)
        {
            XElement BaseWrapperXElement = new XElement("Node");
            BaseWrapperXElement.Add(CreateAttributesForNodeBase(nodeBaseWrapper));

            return BaseWrapperXElement;
        }

        public IEnumerable<XAttribute> CreateAttributesForNodeBase(NodeBaseWrapper nodeBaseWrapper)
        {
            return new XAttribute[] { new XAttribute("Name", nodeBaseWrapper.Node.Name), new XAttribute("Position", nodeBaseWrapper.Position) };
        }

        public void DeserializeCollection(IConnectableItem containerNode, string nodeXmlListPath)
        {
            //IEnumerable<XElement> animationXElementList = XDocument.Load(nodeXmlListPath).Element("Script").Elements("Node");

            //foreach(IConnectableItem node in (containerNode as ContainerNodeWrapper).ConnectableItems)
            //{
                
            //}
        }
    }
}
